﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using umbraco.cms.businesslogic.web;
using umbraco.BusinessLogic;
using umbraco.NodeFactory;
using SPCFMedicineInformer.Helpers;
using Vega.USiteBuilder;
using SPCFMedicineInformer.DocumentTypes;
using SPCFMedicineInformer.Constants;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_MedicineCategoryDetails : System.Web.UI.MasterPage
    {
        int id = 0;
        static int masterCatId = 0;
        static string catName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNew = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                PopulateDropdowns();
                if (id > 0)
                {
                    var node = new Node(id);
                    var c = node != null && node.NodeTypeAlias == "MedicineCategory" ? ContentHelper.GetByNodeId<MedicineCategory>(id) : null;
                    if (c != null)
                    {
                        txtCategoryName.Text = c.Name;
                        taContent.Value = c.Description;
                        cbHideinConsultation.Checked = c.HideInConsultation;
                        catName = c.Name;
                        FormHelper.ShowChildItemsOfCategory(litSubCateogories, litGenericNames, litMedicines, litSymptoms, id, false);
                        
                        Node parentCat = new Node(c.ParentId);//test if parent node is also category - applies to sub categories
                        if (parentCat.NodeTypeAlias == "MedicineCategory")
                        {
                            ddlCategory.SelectedValue = parentCat.Id.ToString();
                            masterCatId = parentCat.Id;
                        }
                        if (isNew)
                            FormHelper.ShowMessage(MessageType.Done, "Medicine Category Succesfully Saved!", MsgLiteral);
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);
                    }
                }
            }
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void Update()
        {
            if (id > 0)
            {
                int catId = int.Parse(ddlCategory.SelectedValue);
                var d = new Document(id);
                if (d != null)
                {
                    TransferDetailsToUmbraco(d);
                    if (catId != masterCatId)
                    {
                        catId = catId == 0 ? UmbracoNodeHelper.GetMedicineContainerNode().Id : catId;//if before was a subcategory now change to main
                        UmbracoNodeHelper.MoveNode(catId, d.Id);
                    }
                        
                }
            }
        }
        int AddNewCategory()
        {
            DocumentType UmbracoDocType = DocumentType.GetByAlias("MedicineCategory");
            int tempInt;
            int masterCatId = int.TryParse(ddlCategory.SelectedValue, out tempInt) ? tempInt : 0;
            Node medContainer = masterCatId == 0 ? UmbracoNodeHelper.GetMedicineContainerNode() : new Node(masterCatId);

            if (medContainer != null)
            {
                Document d = Document.MakeNew(txtCategoryName.Text, UmbracoDocType, User.GetUser(0), medContainer.Id);
                TransferDetailsToUmbraco(d);
                AddSymptomContainer(d.Id);
                return d.Id;
            }
            return 0;
        }
        void AddSymptomContainer(int id)//add default container for symptoms 
        {
            DocumentType UmbracoDocType = DocumentType.GetByAlias("SymptomListing");
            Document d = Document.MakeNew("Symptom Container", UmbracoDocType, User.GetUser(0), id);
            d.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(d.Id);
        }
        void TransferDetailsToUmbraco(Document d)
        {
            d.Text = txtCategoryName.Text;
            d.getProperty(UmbracoPropertyName.CONDITION_DESCRIPTION).Value = taContent.Value;
            d.getProperty(UmbracoPropertyName.HIDE_IN_CONSULTATION).Value = cbHideinConsultation.Checked;
            d.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(d.Id);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    FormHelper.ShowMessage(MessageType.Done, "Medicine Category Succesfully Saved!", MsgLiteral);
                }
                else
                {
                    id = AddNewCategory();
                    Response.Redirect("/admin/utilities/medicine-categories/category-entry.aspx?id=" + id + "&n=1");
                }
            }
        }
        bool IsValidate()
        {
            bool result = true;
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";
            if (string.IsNullOrWhiteSpace(txtCategoryName.Text))
            {
                result = false;
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Category Name is required!"));
            }
            else if (id == 0 || catName.ToLower() != txtCategoryName.Text.ToLower())
            {
                var node = NodeLocator.GetNodesOfExactType<MedicineCategory>().Where(a=>a.Name.ToLower() == txtCategoryName.Text.ToLower()).FirstOrDefault();
                if (node != null)
                {
                    result = false;
                    sb.AppendLine(string.Format(msgFormat, "msg error", "Category Name exist!"));
                } 
            }
            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/medicine-categories");
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/medicine-categories/category-entry");
        }
        void PopulateDropdowns()
        {
            var categoryList = NodeLocator.GetNodesOfExactType<MedicineCategory>().Where(node=>node.GetLevel() == 4 && node.Id != id);
            ddlCategory.Items.Clear();
            ddlCategory.DataSource = categoryList;
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataValueField = "Id";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("Choose...", "0"));
        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/medicine-categories");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
            
    }
}